import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { Save, Plus, Trash2, Edit, AlertTriangle, CheckCircle, Calendar } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, Button, Input, Switch, FormControlLabel, Select, MenuItem, TextareaAutosize } from '@mui/material';
import logger from '../../../utils/logger';

// 样式组件
const Container = styled.div`
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
`;

const ContentWrapper = styled.div`
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
`;

const PageHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
`;

const PageTitle = styled.h1`
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const ActionButton = styled.button`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background-color: #40a9ff;
    transform: translateY(-1px);
  }

  &:active {
    transform: translateY(0);
  }

  &:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
    transform: none;
  }
`;

const Section = styled.div`
  margin-bottom: 32px;
`;

const SectionTitle = styled.h2`
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e0e0e0;
`;

const ConfigTable = styled.div`
  display: grid;
  gap: 16px;
  margin-bottom: 24px;
`;

const ConfigItem = styled.div`
  display: grid;
  grid-template-columns: 200px 1fr 100px;
  gap: 16px;
  align-items: center;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  background-color: ${props => props.isActive ? '#f6ffed' : 'white'};
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
`;

const ConfigLabel = styled.div`
  font-weight: 500;
  color: #333;
`;

const ConfigValue = styled.div`
  color: #666;
`;

const ConfigActions = styled.div`
  display: flex;
  gap: 8px;
  justify-content: flex-end;
`;

const IconButton = styled.button`
  padding: 6px;
  background-color: transparent;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &:hover {
    background-color: #f0f0f0;
  }

  svg {
    width: 16px;
    height: 16px;
  }
`;

const SaveMessage = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  margin-bottom: 24px;
  color: #389e0d;
`;

const CategoryTabs = styled.div`
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
`;

const CategoryTab = styled.button`
  padding: 8px 16px;
  background: none;
  border: none;
  border-bottom: 2px solid ${props => props.active ? '#1890ff' : 'transparent'};
  color: ${props => props.active ? '#1890ff' : '#666'};
  font-size: 14px;
  font-weight: ${props => props.active ? '500' : 'normal'};
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    color: #1890ff;
  }
`;

const BaziAnalysisConfig = () => {
  // 页面加载时记录访问日志
  useEffect(() => {
    logger.info('进入八字分析配置页面');
  }, []);
  // 状态管理
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState('elements');
  const [configData, setConfigData] = useState({
    elements: [],
    zodiacSigns: [],
    interpretations: [],
    globalSettings: {
      isEnabled: true,
      defaultConfidenceThreshold: 0.8,
      includeDetailedAnalysis: true
    }
  });
  const [openEditDialog, setOpenEditDialog] = useState(false);
  const [currentEditItem, setCurrentEditItem] = useState(null);
  const [editType, setEditType] = useState(null);
  const [editForm, setEditForm] = useState({});
  const [saveSuccess, setSaveSuccess] = useState(false);

  // 模拟获取配置数据
  useEffect(() => {
    logger.info('进入八字分析配置管理页面');
    
    const fetchConfigData = async () => {
      try {
        setLoading(true);
        // 在实际应用中，这里应该调用API获取数据
        // const response = await axios.get('/api/admin/bazi-analysis/config');
        // 模拟数据
        setTimeout(() => {
          const mockData = {
            elements: [
              { id: '1', name: '金', description: '代表刚硬、果断、锐利', color: '#F0F0F0', isActive: true },
              { id: '2', name: '木', description: '代表生机、成长、扩张', color: '#52C41A', isActive: true },
              { id: '3', name: '水', description: '代表智慧、流动、适应性', color: '#1890FF', isActive: true },
              { id: '4', name: '火', description: '代表热情、活力、行动力', color: '#FF4D4F', isActive: true },
              { id: '5', name: '土', description: '代表稳定、包容、责任', color: '#FAAD14', isActive: true }
            ],
            zodiacSigns: [
              { id: '1', name: '鼠', description: '机智、敏捷、有洞察力', isActive: true },
              { id: '2', name: '牛', description: '勤劳、踏实、稳重', isActive: true },
              { id: '3', name: '虎', description: '勇敢、果断、有领导力', isActive: true },
              { id: '4', name: '兔', description: '温和、善良、机智', isActive: true },
              { id: '5', name: '龙', description: '权威、自信、创造力强', isActive: true },
              { id: '6', name: '蛇', description: '聪明、神秘、直觉敏锐', isActive: true },
              { id: '7', name: '马', description: '自由、热情、行动力强', isActive: true },
              { id: '8', name: '羊', description: '温顺、友善、富有同情心', isActive: true },
              { id: '9', name: '猴', description: '灵活、聪明、多才多艺', isActive: true },
              { id: '10', name: '鸡', description: '谨慎、细致、有责任心', isActive: true },
              { id: '11', name: '狗', description: '忠诚、正直、可靠', isActive: true },
              { id: '12', name: '猪', description: '诚恳、包容、乐观', isActive: true }
            ],
            interpretations: [
              { id: '1', type: 'element', refId: '1', condition: '金旺', interpretation: '此人性格刚毅，做事果断，但可能过于固执。适合从事金融、法律等需要决断力的工作。', confidenceLevel: 0.85 },
              { id: '2', type: 'element', refId: '2', condition: '木旺', interpretation: '此人充满活力，富有创造力，善于社交。适合从事教育、艺术等需要创造力的工作。', confidenceLevel: 0.8 },
              { id: '3', type: 'element', refId: '3', condition: '水旺', interpretation: '此人聪明机智，适应能力强，但可能缺乏定性。适合从事科研、设计等需要创新思维的工作。', confidenceLevel: 0.8 },
              { id: '4', type: 'element', refId: '4', condition: '火旺', interpretation: '此人性情急躁，热情开朗，精力充沛。适合从事销售、表演等需要表现力的工作。', confidenceLevel: 0.85 },
              { id: '5', type: 'element', refId: '5', condition: '土旺', interpretation: '此人踏实稳重，责任感强，但可能过于保守。适合从事管理、财务等需要稳定的工作。', confidenceLevel: 0.8 },
              { id: '6', type: 'zodiac', refId: '1', condition: '鼠年生人', interpretation: '机智灵活，擅长应变，但可能过于狡猾。适合从事商业、策划等需要智慧的工作。', confidenceLevel: 0.85 },
              { id: '7', type: 'zodiac', refId: '5', condition: '龙年生人', interpretation: '自信权威，领导能力强，但可能过于自负。适合从事领导、管理等需要决策力的工作。', confidenceLevel: 0.9 },
              { id: '8', type: 'zodiac', refId: '9', condition: '猴年生人', interpretation: '聪明灵活，多才多艺，但可能缺乏耐心。适合从事技术、创意等需要智慧的工作。', confidenceLevel: 0.85 },
              { id: '9', type: 'general', refId: '0', condition: '五行平衡', interpretation: '此人命运较为顺遂，身体健壮，事业有成，家庭和睦。', confidenceLevel: 0.9 },
              { id: '10', type: 'general', refId: '0', condition: '五行失衡', interpretation: '此人命运多波折，需要注意调和自身能量，保持心态平衡。', confidenceLevel: 0.85 }
            ],
            globalSettings: {
              isEnabled: true,
              defaultConfidenceThreshold: 0.8,
              includeDetailedAnalysis: true
            }
          };
          setConfigData(mockData);
          setLoading(false);
        }, 500);
      } catch (error) {
        console.error('获取八字分析配置失败:', error);
        setLoading(false);
      }
    };

    fetchConfigData();
  }, []);

  // 获取当前分类的解读
  const getCurrentCategoryInterpretations = () => {
    if (activeCategory === 'elements') {
      return configData.interpretations.filter(item => item.type === 'element');
    } else if (activeCategory === 'zodiacs') {
      return configData.interpretations.filter(item => item.type === 'zodiac');
    } else {
      return configData.interpretations.filter(item => item.type === 'general');
    }
  };

  // 获取引用项名称
  const getRefItemName = (type, refId) => {
    if (type === 'element') {
      const item = configData.elements.find(el => el.id === refId);
      return item ? item.name : '未知';
    } else if (type === 'zodiac') {
      const item = configData.zodiacSigns.find(zs => zs.id === refId);
      return item ? item.name : '未知';
    }
    return '通用';
  };

  // 处理编辑元素
  const handleEditElement = (element) => {
    setCurrentEditItem(element);
    setEditType('element');
    setEditForm({ ...element });
    setOpenEditDialog(true);
  };

  // 处理编辑生肖
  const handleEditZodiac = (zodiac) => {
    setCurrentEditItem(zodiac);
    setEditType('zodiac');
    setEditForm({ ...zodiac });
    setOpenEditDialog(true);
  };

  // 处理编辑解读
  const handleEditInterpretation = (interpretation) => {
    setCurrentEditItem(interpretation);
    setEditType('interpretation');
    setEditForm({ ...interpretation });
    setOpenEditDialog(true);
  };

  // 处理添加新元素
  const handleAddElement = () => {
    setCurrentEditItem(null);
    setEditType('element');
    setEditForm({ name: '', description: '', color: '#999999', isActive: true });
    setOpenEditDialog(true);
  };

  // 处理添加新生肖
  const handleAddZodiac = () => {
    setCurrentEditItem(null);
    setEditType('zodiac');
    setEditForm({ name: '', description: '', isActive: true });
    setOpenEditDialog(true);
  };

  // 处理添加新解读
  const handleAddInterpretation = () => {
    setCurrentEditItem(null);
    setEditType('interpretation');
    let defaultRefId = '0';
    let defaultType = 'general';
    
    if (activeCategory === 'elements' && configData.elements.length > 0) {
      defaultType = 'element';
      defaultRefId = configData.elements[0].id;
    } else if (activeCategory === 'zodiacs' && configData.zodiacSigns.length > 0) {
      defaultType = 'zodiac';
      defaultRefId = configData.zodiacSigns[0].id;
    }
    
    setEditForm({ 
      type: defaultType,
      refId: defaultRefId,
      condition: '', 
      interpretation: '', 
      confidenceLevel: 0.8 
    });
    setOpenEditDialog(true);
  };

  // 处理删除元素
  const handleDeleteElement = (id) => {
    logger.info(`删除五行元素: ${id}`);
    if (window.confirm('确定要删除这个五行元素吗？这将同时删除相关的所有解读。')) {
      setConfigData(prev => ({
        ...prev,
        elements: prev.elements.filter(el => el.id !== id),
        interpretations: prev.interpretations.filter(i => !(i.type === 'element' && i.refId === id))
      }));
    }
  };

  // 处理删除生肖
  const handleDeleteZodiac = (id) => {
    logger.info(`删除生肖: ${id}`);
    if (window.confirm('确定要删除这个生肖吗？这将同时删除相关的所有解读。')) {
      setConfigData(prev => ({
        ...prev,
        zodiacSigns: prev.zodiacSigns.filter(zs => zs.id !== id),
        interpretations: prev.interpretations.filter(i => !(i.type === 'zodiac' && i.refId === id))
      }));
    }
  };

  // 处理删除解读
  const handleDeleteInterpretation = (id) => {
    logger.info(`删除解读: ${id}`);
    if (window.confirm('确定要删除这个解读吗？')) {
      setConfigData(prev => ({
        ...prev,
        interpretations: prev.interpretations.filter(i => i.id !== id)
      }));
    }
  };

  // 处理表单输入变化
  const handleFormChange = (field, value) => {
    setEditForm(prev => ({ ...prev, [field]: value }));
  };

  // 处理保存编辑
  const handleSaveEdit = () => {
    if (editType === 'element') {
      // 记录添加或编辑五行元素
      logger.info(currentEditItem ? 
        `编辑五行元素: ${currentEditItem.id}` : 
        '添加五行元素', 
        { name: editForm.name }
      );
      if (currentEditItem) {
        // 更新现有元素
        setConfigData(prev => ({
          ...prev,
          elements: prev.elements.map(el => 
            el.id === currentEditItem.id ? { ...editForm, id: el.id } : el
          )
        }));
      } else {
        // 添加新元素
        const newElement = {
          ...editForm,
          id: Date.now().toString()
        };
        setConfigData(prev => ({
          ...prev,
          elements: [...prev.elements, newElement]
        }));
      }
    } else if (editType === 'zodiac') {
      // 记录添加或编辑生肖
      logger.info(currentEditItem ? 
        `编辑生肖: ${currentEditItem.id}` : 
        '添加生肖', 
        { name: editForm.name }
      );
      if (currentEditItem) {
        // 更新现有生肖
        setConfigData(prev => ({
          ...prev,
          zodiacSigns: prev.zodiacSigns.map(zs => 
            zs.id === currentEditItem.id ? { ...editForm, id: zs.id } : zs
          )
        }));
      } else {
        // 添加新生肖
        const newZodiac = {
          ...editForm,
          id: Date.now().toString()
        };
        setConfigData(prev => ({
          ...prev,
          zodiacSigns: [...prev.zodiacSigns, newZodiac]
        }));
      }
    } else if (editType === 'interpretation') {
      // 记录添加或编辑解读
      logger.info(currentEditItem ? 
        `编辑解读: ${currentEditItem.id}` : 
        '添加解读', 
        { type: editForm.type, condition: editForm.condition }
      );
      if (currentEditItem) {
        // 更新现有解读
        setConfigData(prev => ({
          ...prev,
          interpretations: prev.interpretations.map(i => 
            i.id === currentEditItem.id ? { ...editForm, id: i.id } : i
          )
        }));
      } else {
        // 添加新解读
        const newInterpretation = {
          ...editForm,
          id: Date.now().toString()
        };
        setConfigData(prev => ({
          ...prev,
          interpretations: [...prev.interpretations, newInterpretation]
        }));
      }
    }
    setOpenEditDialog(false);
  };

  // 处理保存所有配置
  const handleSaveAllConfig = async () => {
    logger.info('保存八字分析所有配置');
    try {
      // 在实际应用中，这里应该调用API保存数据
      // await axios.post('/api/admin/bazi-analysis/config', configData);
      // 模拟保存
      setTimeout(() => {
        setSaveSuccess(true);
        setTimeout(() => setSaveSuccess(false), 3000);
      }, 500);
    } catch (error) {
      console.error('保存配置失败:', error);
    }
  };

  // 处理全局设置变更
  const handleGlobalSettingChange = (field, value) => {
    setConfigData(prev => ({
      ...prev,
      globalSettings: {
        ...prev.globalSettings,
        [field]: value
      }
    }));
  };

  if (loading) {
    return (
      <Container>
        <ContentWrapper>
          <div style={{ display: 'flex', justifyContent: 'center', padding: '48px' }}>
            <div>加载中...</div>
          </div>
        </ContentWrapper>
      </Container>
    );
  }

  return (
    <Container>
      <ContentWrapper>
        <PageHeader>
          <PageTitle>
            <Calendar size={24} />
            八字分析配置管理
          </PageTitle>
          <ActionButton onClick={handleSaveAllConfig}>
            <Save size={16} />
            保存所有配置
          </ActionButton>
        </PageHeader>

        {saveSuccess && (
          <SaveMessage>
            <CheckCircle size={20} />
            配置保存成功！
          </SaveMessage>
        )}

        {/* 全局设置 */}
        <Section>
          <SectionTitle>全局设置</SectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={configData.globalSettings.isEnabled}
                    onChange={(e) => handleGlobalSettingChange('isEnabled', e.target.checked)}
                    color="primary"
                  />
                }
                label="启用八字分析功能"
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <span style={{ minWidth: 150 }}>默认置信度阈值:</span>
              <Input
                type="number"
                min="0"
                max="1"
                step="0.01"
                value={configData.globalSettings.defaultConfidenceThreshold}
                onChange={(e) => handleGlobalSettingChange('defaultConfidenceThreshold', parseFloat(e.target.value))}
                style={{ width: 100 }}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={configData.globalSettings.includeDetailedAnalysis}
                    onChange={(e) => handleGlobalSettingChange('includeDetailedAnalysis', e.target.checked)}
                  />
                }
                label="包含详细分析报告"
              />
            </div>
          </div>
        </Section>

        {/* 分类标签 */}
        <CategoryTabs>
          <CategoryTab active={activeCategory === 'elements'} onClick={() => setActiveCategory('elements')}>五行元素</CategoryTab>
          <CategoryTab active={activeCategory === 'zodiacs'} onClick={() => setActiveCategory('zodiacs')}>十二生肖</CategoryTab>
          <CategoryTab active={activeCategory === 'interpretations'} onClick={() => setActiveCategory('interpretations')}>解读配置</CategoryTab>
        </CategoryTabs>

        {/* 五行元素管理 */}
        {activeCategory === 'elements' && (
          <Section>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <SectionTitle>五行元素管理</SectionTitle>
              <ActionButton onClick={handleAddElement} style={{ backgroundColor: '#52c41a' }}>
                <Plus size={16} />
                添加五行元素
              </ActionButton>
            </div>
            <ConfigTable>
              {configData.elements.map(element => (
                <ConfigItem key={element.id} isActive={element.isActive}>
                  <ConfigLabel>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div 
                        style={{ 
                          width: 16, 
                          height: 16, 
                          backgroundColor: element.color,
                          borderRadius: 4,
                          border: '1px solid #d9d9d9'
                        }} 
                      />
                      {element.name}
                    </div>
                  </ConfigLabel>
                  <ConfigValue>
                    <div>{element.description}</div>
                    <div style={{ color: '#999', fontSize: '12px', marginTop: 4 }}>
                      状态: {element.isActive ? '启用' : '禁用'}
                    </div>
                  </ConfigValue>
                  <ConfigActions>
                    <IconButton onClick={() => handleEditElement(element)} title="编辑">
                      <Edit size={16} color="#1890ff" />
                    </IconButton>
                    <IconButton onClick={() => handleDeleteElement(element.id)} title="删除">
                      <Trash2 size={16} color="#ff4d4f" />
                    </IconButton>
                  </ConfigActions>
                </ConfigItem>
              ))}
            </ConfigTable>
          </Section>
        )}

        {/* 十二生肖管理 */}
        {activeCategory === 'zodiacs' && (
          <Section>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <SectionTitle>十二生肖管理</SectionTitle>
              <ActionButton onClick={handleAddZodiac} style={{ backgroundColor: '#52c41a' }}>
                <Plus size={16} />
                添加生肖
              </ActionButton>
            </div>
            <ConfigTable>
              {configData.zodiacSigns.map(zodiac => (
                <ConfigItem key={zodiac.id} isActive={zodiac.isActive}>
                  <ConfigLabel>{zodiac.name}</ConfigLabel>
                  <ConfigValue>
                    <div>{zodiac.description}</div>
                    <div style={{ color: '#999', fontSize: '12px', marginTop: 4 }}>
                      状态: {zodiac.isActive ? '启用' : '禁用'}
                    </div>
                  </ConfigValue>
                  <ConfigActions>
                    <IconButton onClick={() => handleEditZodiac(zodiac)} title="编辑">
                      <Edit size={16} color="#1890ff" />
                    </IconButton>
                    <IconButton onClick={() => handleDeleteZodiac(zodiac.id)} title="删除">
                      <Trash2 size={16} color="#ff4d4f" />
                    </IconButton>
                  </ConfigActions>
                </ConfigItem>
              ))}
            </ConfigTable>
          </Section>
        )}

        {/* 解读管理 */}
        {activeCategory === 'interpretations' && (
          <Section>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <SectionTitle>{activeCategory === 'elements' ? '五行解读' : activeCategory === 'zodiacs' ? '生肖解读' : '八字解读'}</SectionTitle>
              <ActionButton onClick={handleAddInterpretation} style={{ backgroundColor: '#52c41a' }}>
                <Plus size={16} />
                添加解读
              </ActionButton>
            </div>
            <ConfigTable>
              {getCurrentCategoryInterpretations().map(interpretation => (
                <ConfigItem key={interpretation.id}>
                  <ConfigLabel>
                    {getRefItemName(interpretation.type, interpretation.refId)} - {interpretation.condition}
                  </ConfigLabel>
                  <ConfigValue>
                    <div>{interpretation.interpretation}</div>
                    <div style={{ color: '#999', fontSize: '12px', marginTop: 4 }}>
                      置信度: {(interpretation.confidenceLevel * 100).toFixed(0)}%
                    </div>
                  </ConfigValue>
                  <ConfigActions>
                    <IconButton onClick={() => handleEditInterpretation(interpretation)} title="编辑">
                      <Edit size={16} color="#1890ff" />
                    </IconButton>
                    <IconButton onClick={() => handleDeleteInterpretation(interpretation.id)} title="删除">
                      <Trash2 size={16} color="#ff4d4f" />
                    </IconButton>
                  </ConfigActions>
                </ConfigItem>
              ))}
            </ConfigTable>
          </Section>
        )}

        {/* 编辑对话框 */}
        <Dialog open={openEditDialog} onClose={() => setOpenEditDialog(false)} maxWidth="md">
          <DialogTitle>
          {editType === 'element' ? 
            (currentEditItem ? '编辑五行元素' : '添加五行元素') : 
            editType === 'zodiac' ?
            (currentEditItem ? '编辑生肖' : '添加生肖') :
            (currentEditItem ? '编辑解读' : '添加解读')
          }
        </DialogTitle>
          <DialogContent>
            {editType === 'element' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>元素名称</label>
                  <Input
                    fullWidth
                    value={editForm.name}
                    onChange={(e) => handleFormChange('name', e.target.value)}
                    placeholder="请输入五行元素名称（如：金、木、水、火、土）"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>元素描述</label>
                  <TextareaAutosize
                    fullWidth
                    value={editForm.description}
                    onChange={(e) => handleFormChange('description', e.target.value)}
                    placeholder="请输入元素特性描述"
                    minRows={3}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>元素颜色</label>
                  <Input
                    fullWidth
                    type="color"
                    value={editForm.color}
                    onChange={(e) => handleFormChange('color', e.target.value)}
                  />
                </div>
                <FormControlLabel
                  control={
                    <Switch
                      checked={editForm.isActive}
                      onChange={(e) => handleFormChange('isActive', e.target.checked)}
                    />
                  }
                  label="启用此五行元素"
                />
              </div>
            ) : editType === 'zodiac' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>生肖名称</label>
                  <Input
                    fullWidth
                    value={editForm.name}
                    onChange={(e) => handleFormChange('name', e.target.value)}
                    placeholder="请输入生肖名称（如：鼠、牛、虎等）"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>生肖描述</label>
                  <TextareaAutosize
                    fullWidth
                    value={editForm.description}
                    onChange={(e) => handleFormChange('description', e.target.value)}
                    placeholder="请输入生肖特性描述"
                    minRows={3}
                  />
                </div>
                <FormControlLabel
                  control={
                    <Switch
                      checked={editForm.isActive}
                      onChange={(e) => handleFormChange('isActive', e.target.checked)}
                    />
                  }
                  label="启用此生肖"
                />
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>解读类型</label>
                  <Select
                    fullWidth
                    value={editForm.type}
                    onChange={(e) => handleFormChange('type', e.target.value)}
                  >
                    <MenuItem value="element">五行解读</MenuItem>
                    <MenuItem value="zodiac">生肖解读</MenuItem>
                    <MenuItem value="general">通用解读</MenuItem>
                  </Select>
                </div>
                {(editForm.type === 'element' || editForm.type === 'zodiac') && (
                  <div>
                    <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
                      {editForm.type === 'element' ? '所属五行' : '所属生肖'}
                    </label>
                    <Select
                      fullWidth
                      value={editForm.refId}
                      onChange={(e) => handleFormChange('refId', e.target.value)}
                    >
                      {(editForm.type === 'element' ? configData.elements : configData.zodiacSigns)
                        .filter(item => item.isActive)
                        .map(item => (
                          <MenuItem key={item.id} value={item.id}>{item.name}</MenuItem>
                        ))
                      }
                    </Select>
                  </div>
                )}
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>条件描述</label>
                  <Input
                    fullWidth
                    value={editForm.condition}
                    onChange={(e) => handleFormChange('condition', e.target.value)}
                    placeholder="如：金旺、木弱、鼠年生人等"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>解读内容</label>
                  <TextareaAutosize
                    fullWidth
                    value={editForm.interpretation}
                    onChange={(e) => handleFormChange('interpretation', e.target.value)}
                    placeholder="请输入详细的解读内容"
                    minRows={4}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>置信度</label>
                  <Input
                    fullWidth
                    type="number"
                    min="0"
                    max="1"
                    step="0.01"
                    value={editForm.confidenceLevel}
                    onChange={(e) => handleFormChange('confidenceLevel', parseFloat(e.target.value))}
                  />
                </div>
              </div>
            )}
          </DialogContent>
          <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <Button onClick={() => setOpenEditDialog(false)}>取消</Button>
            <Button onClick={handleSaveEdit} color="primary">保存</Button>
          </div>
        </Dialog>
      </ContentWrapper>
    </Container>
  );
};

export default BaziAnalysisConfig;